package com.sinaapp.gavinzhang.GSpider.plugin.redis;

import com.sinaapp.gavinzhang.GSpider.core.AbstractGWebUrlList;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * 使用redis实现的待访问列表
 * Created by gavin on 15-9-16.
 */
public class RedisCurrentWebUrlList extends AbstractGWebUrlList {
    private Jedis jedis;

    public RedisCurrentWebUrlList(Jedis jedis) {
        this.jedis = jedis;
    }

    @Override
    public boolean exist(String webUrl) {
        //TODO 这里有问题
        /*jedis.lpop("currentUrlList");*/
        return false;
    }

    @Override
    public String get() {
        //如果队列为空则会阻塞，否则返回list，0为队列名，1为内容
        List<String> list =jedis.brpop(0,"currentUrlList");
        //return jedis.rpop("currentUrlList");
        return list.get(1);
    }

    @Override
    public AbstractGWebUrlList add(String webUrl) {
        jedis.lpush("currentUrlList", webUrl);
        return this;
    }

    @Override
    public AbstractGWebUrlList remove(String webUrl) {
        jedis.lrem("currentUrlList", 0, webUrl);
        return this;
    }

    @Override
    public int size() {
        return jedis.llen("currentUrlList").intValue();
    }

    public static void main(String[] args)
    {
        Jedis jedis = new Jedis("localhost");
        RedisCurrentWebUrlList list = new RedisCurrentWebUrlList(jedis);
        list.add("www.baidu.com");
        list.add("www.zhihu.com");
        System.out.println(list.size());

        while (true)
        {
            System.out.println(list.get()+"  "+System.currentTimeMillis()/1000);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
